package org.maxgroundstation.groundstation.comm.service.video;

/**
 * A class for polling the current rate of receiving camera images.
 * @author Scott Davis
 * 
 * Copyright (C) 2010  Scott Davis
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class VideoRatePoller implements Runnable {
	
	// Time (milliseconds) between video rate polls.
	private static final long POLLING_RATE = 1000L;
	
	// Data members
    private float videoRate;
	private long lastPollTime;
	private int numImagesReceived;
	private Thread pollingThread;
	private boolean run;
	
	/**
	 * Constructor
	 */
	public VideoRatePoller() {
		
		// Initiate data members.
		videoRate = 0F;
		lastPollTime = 0L;
		numImagesReceived = 0;
		pollingThread = null;
		run = true;
		
		// Start polling.
		start();
	}
	
	/**
	 * Gets the current video rate.
	 * @return video rate (fps).
	 */
	public float getVideoRate() {
		return videoRate;
	}
	
	/**
	 * Adds a video frame that was received.
	 */
	public void addFrameRecieved() {
		numImagesReceived++;
	}
	
    /**
     * Starts the polling thread.
     */
    public void start() {
        if ((pollingThread == null) || !run) { 
        	pollingThread = new Thread(this, "video polling thread");
        	pollingThread.start();
        }
    }
    
    /**
     * Stops polling the video rate.
     */
    public void stop() {
    	run = false;
    }
	
	@Override
	public void run() {
		run = true;
		while (run) {
			try {
                Thread.sleep(POLLING_RATE);
            } 
            catch (InterruptedException e) {}
            
			long currentTime = System.currentTimeMillis();
			long timeDiff = currentTime - lastPollTime;
			if (timeDiff < ((float) POLLING_RATE * 1.5F)) {
				videoRate = (float) numImagesReceived / ((float) POLLING_RATE / 1000F);
				numImagesReceived = 0;
				// System.out.println("video rate: " + videoRate);
			}
			lastPollTime = currentTime;
		}
	}
}